﻿using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;


namespace Manox.Libs.ODB
{
    /// <summary>
    /// ODB manager inspector.
    /// </summary>
    [CustomEditor(typeof(ObjectDatabaseManager))]
    public class ODBManagerInspector : Editor
    {
        /// <summary>Dungeon.</summary>
        public ObjectDatabaseManager ODBManager { get { return this.target as ObjectDatabaseManager; } }
        /// <summary>Items.</summary>
        private List<ODBInspectorItem> Items;



        /// <summary>
        /// Constructor.
        /// </summary>
        public ODBManagerInspector()
        {
            this.Items = new List<ODBInspectorItem>();
        }

        /// <summary>
        /// On enable.
        /// </summary>
        public void OnEnable()
        {
            this.Initialize();
        }

        /// <summary>
        /// On inspector GUI.
        /// </summary>
        public override void OnInspectorGUI()
        {
            GUILayout.Label("Objects count : " + this.ODBManager.ObjectsCount);

            EditorGUILayout.Separator();

            for (int i = 0; i < this.Items.Count; i++)
                this.Items[i].OnInspectorGUI();
        }

        /// <summary>
        /// Initialize.
        /// </summary>
        private void Initialize()
        {
            this.Items.Clear();

            this.ODBManager.Foreach(this.ProcessObject);            
        }

        /// <summary>
        /// Process object.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        private void ProcessObject(ObjectDatabaseItem item)
        {
            string groupName = item.GetType().ToString();

            ODBInspectorItem groupItem = this.GetGroupItem(groupName);

            if (groupItem == null)
            {
                groupItem = new ODBInspectorItemGroup(groupName);

                this.Items.Add(groupItem);
            }
        }

        /// <summary>
        /// Get group item.
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        private ODBInspectorItem GetGroupItem(string groupName)
        {
            for (int i = 0; i < this.Items.Count; i++)
                if ((this.Items[i] as ODBInspectorItemGroup).GroupName == groupName)
                    return this.Items[i];

            return null;
        }
    }
}
